<template>
  <div class="device-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>设备管理</h2>
      <p>管理设备分组和设备图片</p>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：设备分组管理 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>设备分组管理</h3>
          <el-button type="primary" size="small" @click="handleAddGroup">
            <el-icon><Plus /></el-icon>
            新增分组
          </el-button>
        </div>

        <!-- 分组列表 -->
        <div class="group-list">
          <div
            v-for="group in deviceGroups"
            :key="group.id"
            class="group-item"
            :class="{ active: selectedGroup?.id === group.id }"
            @click="selectGroup(group)"
          >
            <div class="group-info">
              <div class="group-name">{{ group.groupName }}</div>
              <div class="group-count">{{ group.deviceImages?.length || 0 }} 个设备</div>
            </div>
            <div class="group-actions">
              <el-button
                type="text"
                size="small"
                @click.stop="handleEditGroup(group)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="text"
                size="small"
                @click.stop="handleDeleteGroup(group)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：设备图片管理 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>设备图片管理</h3>
          <div class="header-actions">
            <el-select
              v-model="selectedGroupId"
              placeholder="选择分组"
              size="small"
              style="width: 150px; margin-right: 10px;"
              @change="handleGroupChange"
            >
              <el-option label="全部" :value="0" />
              <el-option
                v-for="group in deviceGroups"
                :key="group.id"
                :label="group.groupName"
                :value="group.id"
              />
            </el-select>
            <el-button type="primary" size="small" @click="handleUploadImage">
              <el-icon><Upload /></el-icon>
              上传图片
            </el-button>
          </div>
        </div>

        <!-- 设备图片列表 -->
        <div class="image-list">
          <div
            v-for="image in deviceImages"
            :key="image.id"
            class="image-item"
          >
            <div class="image-preview">
              <img :src="image.imageUrl" :alt="image.imageName" />
            </div>
            <div class="image-info">
              <div class="image-name">{{ image.imageName }}</div>
              <div class="image-details">
                <span>{{ formatFileSize(image.fileSize) }}</span>
                <span>{{ image.groupName }}</span>
              </div>
            </div>
            <div class="image-actions">
              <el-button
                type="text"
                size="small"
                @click="handleEditImage(image)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDownloadImage(image)"
              >
                <el-icon><Download /></el-icon>
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleDeleteImage(image)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 分组编辑对话框 -->
    <el-dialog
      v-model="groupDialog.visible"
      :title="groupDialog.isEdit ? '编辑分组' : '新增分组'"
      width="500px"
    >
      <el-form
        ref="groupFormRef"
        :model="groupDialog.form"
        :rules="groupDialog.rules"
        label-width="80px"
      >
        <el-form-item label="分组名称" prop="groupName">
          <el-input
            v-model="groupDialog.form.groupName"
            placeholder="请输入分组名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number
            v-model="groupDialog.form.sortOrder"
            :min="0"
            :max="999"
            placeholder="排序值越小越靠前"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="groupDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleGroupSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设备图片编辑对话框 -->
    <el-dialog
      v-model="imageDialog.visible"
      title="编辑设备图片"
      width="500px"
    >
      <el-form
        ref="imageFormRef"
        :model="imageDialog.form"
        :rules="imageDialog.rules"
        label-width="80px"
      >
        <el-form-item label="图片名称" prop="imageName">
          <el-input
            v-model="imageDialog.form.imageName"
            placeholder="请输入图片名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所属分组" prop="groupId">
          <el-select
            v-model="imageDialog.form.groupId"
            placeholder="请选择分组"
            style="width: 100%"
          >
            <el-option
              v-for="group in deviceGroups"
              :key="group.id"
              :label="group.groupName"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="imageDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleImageSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 图片上传对话框 -->
    <el-dialog
      v-model="uploadDialog.visible"
      title="上传设备图片"
      width="600px"
    >
      <el-upload
        ref="uploadRef"
        :action="uploadAction"
        :headers="uploadHeaders"
        :data="uploadData"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :file-list="uploadDialog.fileList"
        multiple
        drag
        accept=".svg,.png,.jpg,.jpeg"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传SVG/PNG/JPG文件，且不超过2MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="uploadDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleUploadSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type UploadProps } from 'element-plus'
import { deviceGroupApi, deviceImageApi } from '@/api/deviceGroup'
import type { DeviceGroupVO, DeviceImageVO } from '@/types/circuitDiagram'

// 响应式数据
const deviceGroups = ref<DeviceGroupVO[]>([])
const deviceImages = ref<DeviceImageVO[]>([])
const selectedGroup = ref<DeviceGroupVO | null>(null)
const selectedGroupId = ref(0)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 分组对话框
const groupFormRef = ref<FormInstance>()
const groupDialog = reactive({
  visible: false,
  isEdit: false,
  form: {
    id: 0,
    groupName: '',
    sortOrder: 0
  },
  rules: {
    groupName: [
      { required: true, message: '请输入分组名称', trigger: 'blur' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    sortOrder: [
      { required: true, message: '请输入排序值', trigger: 'blur' }
    ]
  }
})

// 设备图片对话框
const imageFormRef = ref<FormInstance>()
const imageDialog = reactive({
  visible: false,
  form: {
    id: 0,
    imageName: '',
    groupId: 0
  },
  rules: {
    imageName: [
      { required: true, message: '请输入图片名称', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    groupId: [
      { required: true, message: '请选择所属分组', trigger: 'change' }
    ]
  }
})

// 上传对话框
const uploadRef = ref()
const uploadDialog = reactive({
  visible: false,
  fileList: [] as any[]
})

// 上传配置
const uploadAction = '/api/device-image/upload'
const uploadHeaders = {
  // 如果需要认证，在这里添加token
}
const uploadData = {
  groupId: 0
}

// 获取设备分组数据
const getDeviceGroups = async () => {
  try {
    const res = await deviceGroupApi.getAllGroupsWithImages()
    if (res.code === 200) {
      deviceGroups.value = res.data
      if (deviceGroups.value.length > 0 && !selectedGroup.value) {
        selectGroup(deviceGroups.value[0])
      }
    }
  } catch (error) {
    console.error('获取设备分组失败:', error)
    ElMessage.error(`获取设备分组失败: ${error}`)
  }
}

// 获取设备图片数据
const getDeviceImages = async () => {
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      groupId: selectedGroupId.value === 0 ? undefined : selectedGroupId.value
    }
    
    const res = await deviceImageApi.getImagePage(params)
    if (res.code === 200) {
      deviceImages.value = res.data.records
      pagination.total = res.data.total
    }
  } catch (error) {
    console.error('获取设备图片失败:', error)
    ElMessage.error(`获取设备图片失败: ${error}`)
  }
}

// 选择分组
const selectGroup = (group: DeviceGroupVO) => {
  selectedGroup.value = group
  selectedGroupId.value = group.id
  pagination.current = 1
  getDeviceImages()
}

// 分组变化处理
const handleGroupChange = () => {
  pagination.current = 1
  getDeviceImages()
}

// 新增分组
const handleAddGroup = () => {
  groupDialog.isEdit = false
  groupDialog.form = {
    id: null,
    groupName: '',
    sortOrder: 0
  }
  groupDialog.visible = true
}

// 编辑分组
const handleEditGroup = (group: DeviceGroupVO) => {
  groupDialog.isEdit = true
  groupDialog.form = {
    id: group.id,
    groupName: group.groupName,
    sortOrder: group.sortOrder
  }
  groupDialog.visible = true
}

// 删除分组
const handleDeleteGroup = async (group: DeviceGroupVO) => {
  try { await ElMessageBox.confirm(
      `确定要删除分组"${group.groupName}"吗？删除后该分组下的所有设备图片将移至默认分组。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deviceGroupApi.deleteGroup(group.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getDeviceGroups()
      if (selectedGroup.value?.id === group.id) {
        selectedGroup.value = null
        selectedGroupId.value = 0
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分组失败:', error)
      ElMessage.error(`删除分组失败: ${error}`)
    }
  }
}

// 提交分组
const handleGroupSubmit = async () => {
  if (!groupFormRef.value) return
  
  try {
    await groupFormRef.value.validate()
    
    let res
    if (groupDialog.isEdit) {
      res = await deviceGroupApi.updateGroup(groupDialog.form)
    } else {
      res = await deviceGroupApi.createGroup(groupDialog.form)
    }
    
    if (res.code === 200) {
      ElMessage.success(groupDialog.isEdit ? '更新成功' : '创建成功')
      groupDialog.visible = false
      getDeviceGroups()
    }
  } catch (error) {
    console.error('提交分组失败:', error)
    ElMessage.error(`提交失败: ${error}`)
  }
}

// 上传图片
const handleUploadImage = () => {
  uploadDialog.visible = true
  uploadDialog.fileList = []
  uploadData.groupId = selectedGroupId.value === 0 ? 
    (deviceGroups.value[0]?.id || 0) : selectedGroupId.value
}

// 上传前检查
const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = ['image/svg+xml', 'image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidType) {
    ElMessage.error('只能上传SVG/PNG/JPG格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess: UploadProps['onSuccess'] = (response, file) => {
  if (response.code === 200) {
    ElMessage.success(`${file.name} 上传成功`)
    getDeviceImages()
  } else {
    ElMessage.error(`${file.name} 上传失败: ${response.message}`)
  }
}

// 上传失败
const handleUploadError: UploadProps['onError'] = (error, file) => {
  ElMessage.error(`${file.name} 上传失败`)
}

// 提交上传
const handleUploadSubmit = () => {
  uploadDialog.visible = false
  getDeviceImages()
}

// 编辑设备图片
const handleEditImage = (image: DeviceImageVO) => {
  imageDialog.form = {
    id: image.id,
    imageName: image.imageName,
    groupId: image.groupId
  }
  imageDialog.visible = true
}

// 删除设备图片
const handleDeleteImage = async (image: DeviceImageVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备图片"${image.imageName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await deviceImageApi.deleteImage(image.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getDeviceImages()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除设备图片失败:', error)
      ElMessage.error(`删除设备图片失败: ${error}`)
    }
  }
}

// 下载设备图片
const handleDownloadImage = async (image: DeviceImageVO) => {
  try {
    const res = await deviceImageApi.downloadImage(image.id)
    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = image.fileName
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载设备图片失败:', error)
    ElMessage.error(`下载失败: ${error}`)
  }
}

// 提交设备图片
const handleImageSubmit = async () => {
  if (!imageFormRef.value) return
  
  try {
    await imageFormRef.value.validate()
    
    const res = await deviceImageApi.updateImage(imageDialog.form)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      imageDialog.visible = false
      getDeviceImages()
    }
  } catch (error) {
    console.error('更新设备图片失败:', error)
    ElMessage.error(`更新失败: ${error}`)
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getDeviceImages()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  getDeviceImages()
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 页面加载
onMounted(() => {
  getDeviceGroups()
  getDeviceImages()
})
</script>

<style scoped>
.device-manage {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 20px;
  overflow: hidden;
}

.left-panel {
  width: 300px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.right-panel {
  flex: 1;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.group-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.group-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.group-item.active {
  border-color: #409eff;
  background: #e6f7ff;
}

.group-info {
  flex: 1;
}

.group-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.group-count {
  font-size: 12px;
  color: #909399;
}

.group-actions {
  display: flex;
  gap: 5px;
}

.image-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.image-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.image-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.image-preview {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}

.image-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-info {
  padding: 10px;
}

.image-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-details {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}

.image-actions {
  padding: 0 10px 10px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.pagination-wrapper {
  padding: 15px;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: center;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
}
</style> 